package com.ly.juc;

import sun.misc.Unsafe;

import java.sql.Time;
import java.util.concurrent.TimeUnit;

/**
 * @Classname CAS
 * @Description
 * count++线程不安全,count++在编译后不是原子性操作
 * A = count  操作栈开辟变量A 存储count的值
 * B = A + 1.txt  开辟变量B，在变量A的值+1.txt
 * count = B  最后重新赋值给count
 *
 * synchronized和lock可以锁住count++但是效率低下
 *
 * 如果只锁住
 * count = B，效率会提高不少
 * 且count要保证一定的可见性
 *
 * @Date 2020/10/7 17:30
 * @Author 冷心影翼
 */
public class CAS {
	static volatile int number = 0;

	public static synchronized boolean compareAndSwap(int expectValue,int newValue) {
		if(number == expectValue) {
			number = newValue;
			return true;
		}
		return false;
	}

	public static void request() throws InterruptedException {
		TimeUnit.SECONDS.sleep(2);
		while (!compareAndSwap(number,number+1)) {

		}
	}

	public static void main(String[] args) {
		for(int i=0;i<100;i++) {
			new Thread(()->{
				try {
					CAS.request();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}).start();
		}
		while (Thread.activeCount() > 2) {
			Thread.yield();
		}
		System.out.println(number);
	}

}
